<template>
  <div class="assess-list-container">
    <!-- 顶部操作区 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">+ 添加</el-button>
      <div class="filters">
        <el-select v-model="filterOrg" placeholder="组织结构" clearable class="filter-item">
          <el-option label="信息工程学院" value="信息工程学院"/>
          <el-option label="人工智能学院" value="人工智能学院"/>
        </el-select>
        <el-input v-model="filterName" placeholder="请输入姓名" clearable class="filter-item"/>
        <el-input v-model="filterAccount" placeholder="请输入账号" clearable class="filter-item"/>
        <el-input v-model="filterAssessor" placeholder="请输入评估人" clearable class="filter-item"/>
        <div class="filter-actions">
          <el-button icon="Search" type="primary" @click="handleQuery">查询</el-button>
          <el-button icon="Remove" @click="handleRefresh">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-box" style="margin-bottom: 20px;">
      <el-table :data="currentPageTableData" style="width:100%" :header-cell-style="{ 'background-color': '#f5f7fa' }">
        <el-table-column prop="assessTime" label="评估时间" min-width="180" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="account" label="账号" />
        <el-table-column prop="org" label="组织结构" min-width="100"/>
        <el-table-column prop="assessor" label="评估人" />
        <el-table-column prop="warningLevel" label="预警级别">
          <template #default="{ row }">
            <span class="status-dot" :class="getWarningLevelClass(row.warningLevel)"></span>
            <span class="status-text">{{ row.warningLevel }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="closureStatus" label="结案状态" />
        <el-table-column prop="lastUpdate" label="操作时间" min-width="180" />

        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <span class="blue-action" @click="handleView(scope.row)">查看</span>
            <span class="blue-action" @click="handleEdit(scope.row)">编辑</span>
            <span class="red-action" @click="handleDelete(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页可以在这里添加，如果需要的话 -->
    </div>

    <!-- 编辑/添加 弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="dialogMode==='add'?'添加评估记录':(dialogMode==='view'?'查看评估记录':'编辑评估记录')" width="700px">
      <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="120px">

        <!-- 姓名 -->
        <el-form-item label="姓名" prop="name" required>
          <el-input v-if="dialogMode==='add' || dialogMode==='edit'" v-model="editForm.name" placeholder="请输入姓名"/>
          <span v-else-if="dialogMode==='view'">{{ editForm.name }}</span>
          <span v-else>{{ editForm.name }}</span>
        </el-form-item>

        <!-- 评估人 -->
        <el-form-item label="评估人" prop="assessor" required>
          <el-input v-if="dialogMode!=='view'" v-model="editForm.assessor" placeholder="请输入评估人"/>
          <span v-else>{{ editForm.assessor }}</span>
        </el-form-item>

        <!-- 评估内容 -->
        <el-form-item label="评估内容" prop="content" required>
          <el-input v-if="dialogMode!=='view'" type="textarea" v-model="editForm.content" :rows="3" placeholder="请输入评估内容"/>
          <span v-else>{{ editForm.content }}</span>
        </el-form-item>

        <!-- 预警级别 -->
        <el-form-item label="预警级别" prop="warningLevel" required>
          <el-select v-if="dialogMode!=='view'" v-model="editForm.warningLevel" placeholder="请选择预警级别">
            <el-option label="正常适应" value="正常适应" />
            <el-option label="轻度关注" value="轻度关注" />
            <el-option label="重点关注" value="重点关注" />
            <el-option label="高度风险" value="高度风险" />
            <el-option label="危机状态" value="危机状态" />
          </el-select>
          <span v-else>{{ editForm.warningLevel }}</span>
        </el-form-item>

        <!-- 干预级别 -->
        <el-form-item label="干预级别" prop="interventionLevel" required>
          <el-select v-if="dialogMode!=='view'" v-model="editForm.interventionLevel" placeholder="请选择干预级别">
            <el-option label="常规支持" value="normal" />
            <el-option label="一般干预" value="general" />
            <el-option label="加强干预" value="enhanced" />
            <el-option label="重点干预" value="focused" />
            <el-option label="危机干预" value="crisis" />
          </el-select>
          <span v-else>{{ editForm.interventionLevel }}</span>
        </el-form-item>

        <!-- 评估时间 -->
        <el-form-item label="评估时间" prop="assessTime" required>
          <el-date-picker v-if="dialogMode!=='view'"
            v-model="editForm.assessTime"
            type="datetime"
            placeholder="选择日期和时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
          <span v-else>{{ editForm.assessTime }}</span>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input v-if="dialogMode!=='view'" v-model="editForm.remark" type="textarea" :rows="3" placeholder="请输入备注"/>
          <span v-else>{{ editForm.remark }}</span>
        </el-form-item>

        <!-- 结案状态 -->
        <el-form-item label="结案状态" prop="closureStatus">
          <el-select v-if="dialogMode!=='view'" v-model="editForm.closureStatus" placeholder="请选择结案状态">
            <el-option label="未结案" value="未结案" />
            <el-option label="解除预警" value="解除预警" />
            <el-option label="转介" value="转介" />
          </el-select>
          <span v-else>{{ editForm.closureStatus }}</span>
        </el-form-item>

        <!-- 上传文件 -->
        <el-form-item label="上传文件">
          <div v-if="dialogMode!=='view'" class="upload-wrapper">
            <el-upload action="#" :before-upload="beforeUpload" :show-file-list="true" :limit="1">
              <el-button type="primary">选取文件</el-button>
            </el-upload>
            <div class="file-tip">
              只能上传 <span class="file-highlight">excel, word, ppt, zip</span> 文件，且 <span class="file-highlight">不超过2M</span>
            </div>
          </div>
          <span v-else>心理干预记录.docx</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="dialogMode!=='view'" @click="resetEditForm">重置</el-button>
          <el-button v-if="dialogMode!=='view'" type="primary" @click="handleSaveEdit">{{ dialogMode==='add'?'创建':'保存修改' }}</el-button>
          <el-button v-if="dialogMode==='view'" @click="editDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const pageSize = ref(10)
const currentPage = ref(1)

const tableData = ref([
  { id: 1, assessTime: '2025-03-21 11:18', name: '李明', account: '20250001', org: '计算机学院', assessor: '张老师', warningLevel: '危机状态', closureStatus: '未结案', lastUpdate: '2025-03-21 11:18', remark: '该生学习态度良好' },
  { id: 2, assessTime: '2025-03-21 11:19', name: '张亮亮', account: '20250002', org: '软件学院', assessor: '李老师', warningLevel: '高度风险', closureStatus: '解除预警', lastUpdate: '2025-04-22 09:30', remark: '需要持续关注' },
  { id: 3, assessTime: '2025-03-21 11:20', name: '王小明', account: '20250003', org: '人工智能学院', assessor: '王老师', warningLevel: '正常适应', closureStatus: '转介', lastUpdate: '2025-03-21 11:20', remark: '表现良好' }
])
const tableDataCopy = ref([])
const currentPageTableData = ref([])

const sortField = ref('assessTime')
const sortOrder = ref('asc')

const filterOrg = ref('')
const filterName = ref('')
const filterAccount = ref('')
const filterAssessor = ref('')

const editDialogVisible = ref(false)
const dialogMode = ref('view')

const editFormRef = ref(null)
const editForm = ref({
  id: null,
  name: '',
  assessor: '',
  content: '',
  warningLevel: '',
  interventionLevel: '',
  closureStatus: '未结案',
  file: null,
  assessTime: '',
  remark: ''
})

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  assessor: [{ required: true, message: '请填写评估人', trigger: 'blur' }],
  content: [{ required: true, message: '请填写评估内容', trigger: 'blur' }],
  assessTime: [{ required: true, message: '请选择评估时间', trigger: 'change' }],
  warningLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  interventionLevel: [{ required: true, message: '请选择干预级别', trigger: 'change' }]
}

const handleQuery = () => {
  const result = tableDataCopy.value.filter(item =>
      (!filterOrg.value || item.org.includes(filterOrg.value)) &&
      (!filterName.value || item.name.includes(filterName.value)) &&
      (!filterAccount.value || item.account.includes(filterAccount.value)) &&
      (!filterAssessor.value || item.assessor.includes(filterAssessor.value))
  )
  tableData.value = result
  handleCurrentChange(1)
}

const handleRefresh = () => {
  tableData.value = [...tableDataCopy.value]
  filterOrg.value = ''
  filterName.value = ''
  filterAccount.value = ''
  filterAssessor.value = ''
  handleCurrentChange(1)
}

const sortTable = prop => {
  if (sortField.value === prop) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortField.value = prop
    sortOrder.value = prop === 'lastUpdate' ? 'desc' : 'asc'
  }
  tableData.value.sort((a, b) => {
    let valA = a[prop], valB = b[prop]
    if (prop === 'assessTime' || prop === 'lastUpdate') {
      return sortOrder.value === 'asc' ? new Date(valA) - new Date(valB) : new Date(valB) - new Date(valA)
    }
    return sortOrder.value === 'asc'
        ? String(valA).localeCompare(String(valB))
        : String(valB).localeCompare(String(valA))
  })
  handleCurrentChange(currentPage.value)
}

const handleCurrentChange = newPage => {
  const start = (newPage - 1) * pageSize.value
  const end = start + pageSize.value
  currentPageTableData.value = tableData.value.slice(start, end)
}

const handleSizeChange = newPageSize => {
  pageSize.value = newPageSize
  currentPageTableData.value = tableData.value.slice(0, newPageSize)
  currentPage.value = 1
}

onMounted(() => {
  tableDataCopy.value = [...tableData.value]
  currentPageTableData.value = tableData.value.slice(0, pageSize.value)
})

const handleView = row => {
  dialogMode.value = 'view'
  editForm.value = {
    ...row,
    file: null,
    content: '无',  // 评估内容为"无"
    warningLevel: row.warningLevel || '危机状态',
    interventionLevel: '危机干预',
    closureStatus: row.closureStatus || '未结案'
  }
  editDialogVisible.value = true
}

const handleAdd = () => {
  dialogMode.value = 'add'
  editForm.value = { id: null, name: '', assessor: '', content: '', warningLevel: '', interventionLevel: '', closureStatus: '未结案', file: null, assessTime: '', remark: '' }
  editDialogVisible.value = true
}

const handleEdit = (row) => {
  dialogMode.value = 'edit'
  editForm.value = {
    ...row,
    file: null,
    warningLevel: row.warningLevel || '',
    interventionLevel: row.interventionLevel || '',
    closureStatus: row.closureStatus || '未结案'
  }
  editDialogVisible.value = true
}

const beforeUpload = file => {
  const isAllowed = ['excel', 'word', 'presentation', 'zip'].some(ext => file.type.includes(ext))
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isAllowed) {
    ElMessage.error('只能上传 Excel / Word / PPT / Zip 文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传文件不能超过2MB!')
    return false
  }
  editForm.value.file = file
  return true
}

const handleSaveEdit = () => {
  if (dialogMode.value === 'add') {
    const newId = tableData.value.length ? Math.max(...tableData.value.map(d => d.id)) + 1 : 1
    const newRecord = {
      ...editForm.value,
      id: newId,
      lastUpdate: new Date().toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }).replace(/\//g, '-')
    }
    tableData.value.push(newRecord)
    tableDataCopy.value = [...tableData.value]
    handleCurrentChange(currentPage.value)
    ElMessage.success('添加成功')
  } else {
    const idx = tableData.value.findIndex(item => item.id === editForm.value.id)
    if (idx !== -1) {
      tableData.value[idx] = { ...editForm.value, lastUpdate: new Date().toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }).replace(/\//g, '-') }
      tableDataCopy.value = [...tableData.value]
      handleCurrentChange(currentPage.value)
      ElMessage.success('保存成功')
    }
  }
  editDialogVisible.value = false
}

const handleDelete = row => {
  ElMessageBox.confirm(
    '确定要删除该条记录吗?',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    tableData.value = tableData.value.filter(item => item.id !== row.id)
    tableDataCopy.value = [...tableData.value]
    handleCurrentChange(currentPage.value)
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  });
}

const getWarningLevelClass = (level) => {
  switch (level) {
    case '危机状态':
      return 'status-high';
    case '高度风险':
      return 'status-medium';
    case '正常适应':
      return 'status-low';
    default:
      return '';
  }
};

const resetEditForm = () => {
  if (editFormRef.value) editFormRef.value.resetFields()
}
</script>

<style scoped>
.assess-list-container { padding: 20px; }
.action-bar { display: flex; align-items: flex-start; margin-bottom: 16px; }
.filters { display: flex; flex-wrap: wrap; margin-left: 20px; gap: 12px; }
.filter-item { width: 200px; }
.filter-actions { display: flex; align-items: center; gap: 10px; }
.table-box { margin-bottom: 20px; }

/* 对话框底部按钮样式 */
.dialog-footer {
  text-align: right;
}

/* 排序箭头样式 - 与干预时间相同 */
.sortable-header {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
}
.sort-arrows {
  display: flex;
  flex-direction: column;
  margin-left: 4px;
  gap: 1px;
}
.arrow-up,
.arrow-down {
  color: #ccc;
  transition: color 0.2s;
}
.arrow-up.active {
  color: #409EFF;
}
.arrow-down.active {
  color: #409EFF;
}
.arrow-up:hover,
.arrow-down:hover {
  color: #666;
}

/* 旧的排序样式，可以删除或保留兼容 */
.sort-icons { display: flex; flex-direction: column; margin-left: 4px; line-height: 6px; }
.arrow { border: solid #ccc; border-width: 0 2px 2px 0; display: inline-block; padding: 3px; margin: 1px 0; transform: rotate(-135deg); transition: border-color 0.2s; }
.arrow.up { transform: rotate(-135deg); }
.arrow.down { transform: rotate(45deg); }
.arrow.active { border-color: #409EFF; }

.blue-action { color: #409EFF; margin-right: 12px; cursor: pointer; user-select: none; }
.red-action { color: #F56C6C; margin-right: 12px; cursor: pointer; user-select: none; }
.upload-wrapper { display: flex; flex-direction: column; position: relative; }
.file-tip { font-size: 12px; color: #666; margin-top: 4px; }
.file-tip .file-highlight { color: #F56C6C; font-weight: 600; }
.reset-btn { background: transparent; border: none; color: #606266; }

/* 预警级别状态样式 */
.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
}

.status-text {
  font-weight: bold;
}

.status-high {
  background-color: red;
}

.status-medium {
  background-color: orange;
}

.status-low {
  background-color: green;
}
</style>
